package com.tuniu.agents.impl.trip;

import com.tuniu.agents.advisor.ChatEnvironmentMemory;
import com.tuniu.agents.agent.AgentManagerGroup;
import com.tuniu.agents.agent.AgentOptions;
import com.tuniu.agents.agent.OptionsAgent;
import com.tuniu.agents.common.message.BaseAgentNewResp;
import com.tuniu.agents.util.HttpManager;
import com.tuniu.agents.util.JsonUtil;
import com.tuniu.agents.util.WebClientManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.Message;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class Recommend extends OptionsAgent {
    public static final String AGENT_ID = "RECOMMEND_AGENT";
    public static final String PROMPT_ID = "trip_recommend_agent";
    public static final String TRIP_RECOMMEND_KEY = "TRIP_RECOMMEND_KEY";

    private final String tripRecommendTargetUrl;
    private final Map<String, String> headers;
    private final HttpManager httpManager;
    private final ChatEnvironmentMemory chatEnvironmentMemory;

    public Recommend(AgentManagerGroup agentManagerGroup,
                       String agentId,
                       String promptTemplatedId,
                       String tripRecommendTargetUrl,
                       ChatEnvironmentMemory chatEnvironmentMemory) {
        this(agentManagerGroup, agentId, promptTemplatedId, tripRecommendTargetUrl, new HashMap<>(), chatEnvironmentMemory);
    }
    
    public Recommend(AgentManagerGroup agentManagerGroup,
                       String agentId,
                       String promptTemplatedId,
                       String tripRecommendTargetUrl,
                       Map<String, String> headers,
                       ChatEnvironmentMemory chatEnvironmentMemory) {
        super(agentManagerGroup, new AgentOptions(agentId, promptTemplatedId));
        this.tripRecommendTargetUrl = tripRecommendTargetUrl;
        this.headers = headers;
        this.httpManager = new WebClientManager();
        this.chatEnvironmentMemory = chatEnvironmentMemory;
    }
    
    @Override
    public Flux<String> stream(String conversationId, List<Message> messages, Map<String, Object> context) {
        String message = messages.get(0).getText();
        log.info("TripRecommendAgent processing conversation data: {}, Product ID: {}", conversationId, message);
        try {
            String recommendation = call(conversationId, message);
            return Flux.just(recommendation);
        } catch (Exception e) {
            log.error("TripRecommendAgent: Error processing product recommendation", e);
            return Flux.just(BaseAgentNewResp.sendAnswerMsg(null, "Failed to get product recommendation: " + e.getMessage()));
        }
    }

    @Override
    public String call(String conversationId, List<Message> messages, Map<String, Object> context) {
        String message = messages.get(0).getText();
        log.info("TripRecommendAgent processing conversation data: {}, Product ID: {}", conversationId, message);
        if(message == null || message.isEmpty()){
            return null;
        }
        try {
            String[] productIds = message.split(",");
            Map<String, String> productInfoMap = new HashMap<>();
            for(String productId : productIds){
                String recommendation = getProductInfo(conversationId, productId);
                productInfoMap.put(productId, recommendation);
            }
            chatEnvironmentMemory.add(conversationId, Map.of(TRIP_RECOMMEND_KEY, productInfoMap));
            return message;
        } catch (Exception e) {
            log.error("TripRecommendAgent: Error processing product recommendation", e);
            
        }
        return null;
    }

    /**
     * Get product information
     * @return
     */
    private String getProductInfo(String conversationId, String productId){
        log.info("TripRecommendAgent calling recommendation service, Conversation ID: {}, Product ID: {}", conversationId, productId);
        try {
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("productId", productId);
            requestBody.put("journeyId", 0);
            
            String response = httpManager.post(tripRecommendTargetUrl, requestBody, String.class, headers);
            log.info("TripRecommendAgent received product recommendation response, Conversation ID: {}, Product ID: {}, Response: {}", conversationId, productId, response);
            
            if (response == null || response.isEmpty()) {
                return "Sorry, we couldn't retrieve the recommendation information for this product.";
            }
            Map<String, Object> responseMap = JsonUtil.fromJson(response, Map.class);
            if (responseMap != null && responseMap.containsKey("recommendation")) {
                String recommendation = (String) responseMap.get("recommendation");
                return recommendation;
            } else {
                log.info("TripRecommendAgent: No detailed recommendation information available for this product, Conversation ID: {}, Product ID: {}", conversationId, productId);
                return "";
            }
        } catch (Exception e) {
            log.error("TripRecommendAgent: Error calling recommendation service, Conversation ID: {}, Product ID: {}", conversationId, productId, e);
            return "An error occurred while retrieving product recommendation information. Please try again later.";
        }
    }

} 